package com.atguigu.tingshu.live.api;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.model.live.FromUser;
import com.atguigu.tingshu.model.live.SocketMsg;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@Tag(name = "直播间即时通信接口")
@RestController
@ServerEndpoint("/api/websocket/{liveRoomId}/{token}")
public class WebSocketController {


    private static RedisTemplate redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate){
        WebSocketController.redisTemplate = redisTemplate;
    }

    @OnOpen
    public void  onOpen(Session session, @PathParam("liveRoomId") Long liveRoomId, @PathParam("token")String token){
        log.info("建立连接。liveRoomId：{}，token：{}", liveRoomId, token);

        // 根据token查询用户信息
        UserInfoVo userInfo = (UserInfoVo)redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);

        // 构建用户基本信息
        FromUser fromUser = new FromUser();
        fromUser.setUserId(userInfo.getId());
        fromUser.setNickname(userInfo.getNickname());
        fromUser.setAvatarUrl(userInfo.getAvatarUrl());
        // 添加到容器工具类
        WebSocketLocalContainer.addUserToLiveRoom(liveRoomId, userInfo.getId());
        WebSocketLocalContainer.addFromUser(userInfo.getId(), fromUser);
        WebSocketLocalContainer.addSession(userInfo.getId(), session);

        // 进入直播间提示
        SocketMsg socketMsg = new SocketMsg();
        socketMsg.setMsgType(SocketMsg.MsgTypeEnum.JOIN_CHAT.getCode());
        socketMsg.setMsgContent(userInfo.getNickname() + "加入了直播间！");
        socketMsg.setTime(new DateTime().toString("HH:mm:ss"));
        socketMsg.setFromUser(fromUser);
        socketMsg.setLiveRoomId(liveRoomId);
        // 发送消息
        //WebSocketLocalContainer.sendMsg(socketMsg);
        redisTemplate.convertAndSend(RedisConstant.LIVE_CHAT_CHANNEL,socketMsg);



    }

    @OnClose
    public void onClose(Session session, @PathParam("liveRoomId")Long liveRoomId, @PathParam("token")String token){
        log.info("关闭连接。liveRoomId：{}，token：{}", liveRoomId, token);

        // 根据token查询用户信息
        UserInfoVo userInfo = (UserInfoVo)redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        FromUser fromUser = WebSocketLocalContainer.getFromUser(userInfo.getId());

        // 从容器中移除用户
        WebSocketLocalContainer.removeUserFromLiveRoom(liveRoomId, userInfo.getId());
        WebSocketLocalContainer.removeFromUser(userInfo.getId());
        WebSocketLocalContainer.removeSession(userInfo.getId());

        // 退出直播间提示
        SocketMsg socketMsg = new SocketMsg();
        socketMsg.setMsgType(SocketMsg.MsgTypeEnum.JOIN_CHAT.getCode());
        socketMsg.setMsgContent(userInfo.getNickname() + "离开了直播间！");
        socketMsg.setTime(new DateTime().toString("HH:mm:ss"));
        // 构建用户基本信息
        socketMsg.setFromUser(fromUser);
        socketMsg.setLiveRoomId(liveRoomId);
        // 发送消息
        //WebSocketLocalContainer.sendMsg(socketMsg);
        redisTemplate.convertAndSend(RedisConstant.LIVE_CHAT_CHANNEL,socketMsg);

    }

    @OnMessage
    public void onMessage(Session session, String msg){
        log.info("获取了消息。消息内容：{}", msg);
       // WebSocketLocalContainer.sendMsg(JSON.parseObject(msg, SocketMsg.class));
        redisTemplate.convertAndSend(RedisConstant.LIVE_CHAT_CHANNEL,JSON.parseObject(msg,SocketMsg.class));
    }

    @OnError
    public void onError(Session session, Throwable err){
        log.info("连接出错。错误信息：{}", err.getMessage());
        err.printStackTrace();
    }

}
